package com.fh.service.impl;

import com.fh.config.UserLoginClient;
import com.fh.model.Users;
import com.fh.service.UserLoginService;
import com.fh.utils.ResultState;
import com.fh.vo.ResultVo;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Resource
    private UserLoginClient userLoginClient;


    @Override
    public ResultVo login(String userName, String userPwd) {
        Users user = userLoginClient.queryUser(userName);

        if (user==null){
            return  new  ResultVo(ResultState.NO,"账号不存在",null);
        }else {
            if (user.getPassword().equals(userPwd)){
                Map map=new HashMap();
                JwtBuilder builder= Jwts.builder();
                String token=builder.setSubject(userName)
                        .setIssuedAt(new Date())
                        .setId(String.valueOf(user.getUserId()))
                        .setClaims(map)
                        .setExpiration(new Date(System.currentTimeMillis()+30*1000000))
                        .signWith(SignatureAlgorithm.HS256, "xukun")
                        .compact();
                return  new  ResultVo(ResultState.OK,token,user);
            }
            else {
                return  new  ResultVo(501,"密码错误",null);
            }
        }
    }
}
